<template>
  <div class="h-full flex flex-col bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow">
      <div class="px-4 sm:px-6 lg:px-8 py-2 flex justify-between items-center">
        <h1 class="text-xl font-semibold text-gray-900">轻语</h1>
        <div class="flex items-center space-x-4">
          <span>{{ authStore.user?.username }}</span>
          <button @click="authStore.logout" class="text-sm text-gray-700 hover:text-gray-900">退出</button>
        </div>
      </div>
    </header>

    <!-- 主区域 -->
    <main class="flex-1 flex overflow-hidden">
      <!-- 左侧边栏 -->
      <aside class="w-80 bg-white border-r border-gray-200 flex flex-col">
        <!-- 用户信息 -->
        <div class="p-4 border-b border-gray-200">
          <div class="flex items-center">
            <UserAvatar
              :username="authStore.user?.username"
              :avatar="authStore.user?.avatar"
              :userId="'me'"
              size="md"
              :clickable="true"
            />
            <div class="ml-3">
              <div class="font-medium">{{ authStore.user?.username }}</div>
              <div class="text-xs text-gray-500 flex items-center">
                <span class="inline-block h-2 w-2 rounded-full bg-green-500 mr-1"></span>
                <span>在线</span>
              </div>
            </div>
            <div class="ml-auto flex items-center space-x-2">
              <button
                @click="showAddFriendModal = true"
                class="text-gray-400 hover:text-gray-600"
                title="添加好友"
              >
                <span class="text-xl">+</span>
              </button>
            </div>
          </div>
        </div>

        <!-- 搜索框 -->
        <div class="p-4 border-b border-gray-200">
          <div class="relative">
            <input
              v-model="globalSearchKeyword"
              @input="handleGlobalSearch"
              @focus="showGlobalSearchResults = true"
              @blur="handleSearchBlur"
              type="text"
              placeholder="搜索联系人或聊天记录"
              class="form-input pl-8 py-2 text-sm w-full"
            />
            <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
              🔍
            </span>
            <!-- 清空搜索按钮 -->
            <button 
              v-if="globalSearchKeyword.trim()"
              @click="clearGlobalSearch"
              class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
              title="清空搜索"
            >
              ✕
            </button>
          </div>
          
          <!-- 全局搜索结果 -->
          <div v-if="showGlobalSearchResults && globalSearchKeyword.trim().length >= 2" class="absolute z-30 w-80 mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-96 overflow-y-auto">
            <div v-if="globalSearchLoading" class="p-4 text-center text-gray-500">
              <div class="animate-spin inline-block w-4 h-4 border-[2px] border-current border-t-transparent text-blue-600 rounded-full mr-2"></div>
              搜索中...
            </div>
            <div v-else>
              <!-- 联系人搜索结果 -->
              <div v-if="filteredContacts.length > 0">
                <div class="px-3 py-2 text-xs font-medium text-gray-500 bg-gray-50 border-b">联系人</div>
                <div
                  v-for="contact in filteredContacts.slice(0, 5)"
                  :key="contact._id"
                  @mousedown="openContactChat(contact)"
                  class="px-3 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-0"
                >
                  <div class="flex items-center">
                    <UserAvatar
                      :username="contact.username"
                      :avatar="contact.avatar"
                      :userId="contact._id"
                      size="sm"
                      class="mr-2"
                    />
                    <div class="flex-1 min-w-0">
                      <div class="font-medium text-sm truncate" v-html="highlightSearchKeyword(contact.username)"></div>
                      <div class="text-xs text-gray-500">
                        {{ contact.isGroup ? `群组 · ${contact.memberCount || 0}人` : '好友' }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 聊天记录搜索结果 -->
              <div v-if="filteredChats.length > 0">
                <div class="px-3 py-2 text-xs font-medium text-gray-500 bg-gray-50 border-b">最近聊天</div>
                <div
                  v-for="chat in filteredChats.slice(0, 5)"
                  :key="chat._id"
                  @mousedown="openContactChat(chat)"
                  class="px-3 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-100 last:border-0"
                >
                  <div class="flex items-center">
                    <UserAvatar
                      v-if="!chat.isGroup"
                      :username="chat.username"
                      :avatar="chat.avatar"
                      :userId="chat._id"
                      size="sm"
                      class="mr-2"
                    />
                    <div v-else class="h-8 w-8 rounded-full bg-indigo-100 text-lg flex items-center justify-center mr-2">
                      {{ processGroupAvatar(chat.avatar) }}
                    </div>
                    <div class="flex-1 min-w-0">
                      <div class="font-medium text-sm truncate" v-html="highlightSearchKeyword(chat.username)"></div>
                      <div class="text-xs text-gray-500 truncate" v-html="highlightSearchKeyword(chat.lastMessage.content)"></div>
                    </div>
                    <div v-if="chat.unreadCount > 0" class="ml-2 h-4 w-4 bg-red-500 rounded-full flex items-center justify-center text-white text-xs">
                      {{ chat.unreadCount }}
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 无搜索结果 -->
              <div v-if="filteredContacts.length === 0 && filteredChats.length === 0" class="px-3 py-4 text-center text-gray-500 text-sm">
                <div class="text-2xl mb-1">🔍</div>
                未找到相关内容
              </div>
            </div>
          </div>
        </div>

        <!-- 导航标签 -->
        <div class="flex border-b border-gray-200">
          <button
            @click="chatStore.setActiveTab('chats')"
            class="flex-1 py-3 text-center text-sm font-medium"
            :class="chatStore.activeTab === 'chats' ? 'text-primary border-b-2 border-primary' : 'text-gray-500'"
          >
            聊天
            <span v-if="chatStore.unreadMessageCount > 0" class="ml-1 inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
              {{ chatStore.unreadMessageCount }}
            </span>
          </button>
          <button
            @click="chatStore.setActiveTab('contacts')"
            class="flex-1 py-3 text-center text-sm font-medium"
            :class="chatStore.activeTab === 'contacts' ? 'text-primary border-b-2 border-primary' : 'text-gray-500'"
          >
            联系人
            <span v-if="friendRequestsCount > 0 || groupInvitationsCount > 0 || unreadGroupMessagesCount > 0" class="ml-1 inline-flex items-center px-1.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
              {{ friendRequestsCount + groupInvitationsCount + unreadGroupMessagesCount }}
            </span>
          </button>
        </div>

        <!-- 列表区域 -->
        <div class="flex-1 overflow-y-auto">
          <!-- 聊天列表 -->
          <div v-if="chatStore.activeTab === 'chats'" class="divide-y divide-gray-200">
            <div
              v-for="chat in chatStore.chats"
              :key="chat._id"
              @click="chat.isGroup ? openGroupChat(chat._id.replace('group_', '')) : openChatWithFriend(chat._id)"
              class="p-4 hover:bg-gray-50 cursor-pointer"
              :class="{ 'bg-gray-50': chatStore.currentChat === chat._id }"
            >
              <div class="flex">
                <!-- 私聊头像 -->
                <UserAvatar
                  v-if="!chat.isGroup"
                  :username="chat.username"
                  :avatar="chat.avatar"
                  :userId="chat._id"
                  size="md"
                  :clickable="true"
                />
                <!-- 群聊头像 -->
                <div
                  v-else
                  class="h-10 w-10 rounded-full flex items-center justify-center bg-indigo-100 text-2xl"
                >
                  {{ processGroupAvatar(chat.avatar) }}
                </div>
                <div class="ml-3 flex-1">
                  <div class="flex items-center justify-between">
                    <div class="font-medium flex items-center">
                      {{ chat.username }}
                      <span v-if="chat.isGroup" class="ml-1 text-xs px-1.5 py-0.5 bg-blue-100 text-blue-700 rounded-full">群聊</span>
                      <span v-if="chat.isGroup && chat.memberCount" class="ml-1 text-xs text-gray-500">
                        ({{ chat.memberCount }}人)
                      </span>
                    </div>
                    <div class="text-xs text-gray-500">
                      {{ formatTime(chat.lastMessage.createdAt) }}
                    </div>
                  </div>
                  <div class="text-sm text-gray-500 truncate">
                    {{ chat.lastMessage.content }}
                  </div>
                </div>
                <div v-if="chat.unreadCount > 0" class="ml-2 h-5 w-5 bg-red-500 rounded-full flex items-center justify-center text-white text-xs">
                  {{ chat.unreadCount }}
                </div>
              </div>
            </div>
            <div v-if="chatStore.chats.length === 0" class="p-4 text-center text-gray-500">
              暂无聊天记录
            </div>
          </div>

          <!-- 联系人列表 -->
          <div v-else-if="chatStore.activeTab === 'contacts'" class="divide-y divide-gray-200">
            <!-- 好友请求区域 -->
            <div v-if="chatStore.friendRequests.length > 0" class="p-2 bg-gray-50">
              <div class="font-medium text-sm p-2">好友请求</div>
              <div v-for="request in chatStore.friendRequests" :key="request._id" class="p-2 bg-white rounded-md mb-2 last:mb-0">
                <div class="flex items-center">
                  <div
                    class="h-8 w-8 rounded-full bg-gray-300 flex items-center justify-center text-gray-700 font-semibold cursor-pointer"
                    @click="viewUserProfile(request.from._id)"
                  >
                    <div v-if="request.from.avatar" class="h-full w-full rounded-full bg-cover bg-center" :style="`background-image: url('${request.from.avatar}')`"></div>
                    <template v-else>{{ request.from.username[0].toUpperCase() }}</template>
                  </div>
                  <div class="ml-2 flex-1">
                    <div class="font-medium text-sm">{{ request.from.username }}</div>
                    <div class="text-xs text-gray-500">请求添加您为好友</div>
                  </div>
                </div>
                <div class="mt-2 flex space-x-2">
                  <button
                    @click="handleFriendRequest(request._id, 'accepted')"
                    class="flex-1 py-1 text-xs bg-primary text-white rounded"
                  >
                    接受
                  </button>
                  <button
                    @click="handleFriendRequest(request._id, 'rejected')"
                    class="flex-1 py-1 text-xs bg-gray-200 text-gray-700 rounded"
                  >
                    拒绝
                  </button>
                </div>
              </div>
            </div>

            <!-- 群组邀请通知区域 -->
            <div v-if="groupInvitations.length > 0" class="p-3 bg-gray-50 border-t border-gray-200">
              <div class="mb-2">
                <GroupInvitations @invitation-responded="handleGroupInvitationResponse" />
              </div>
            </div>

            <!-- 我的群组标题 -->
            <div class="p-3 bg-gray-50 flex justify-between items-center">
              <div class="font-medium text-sm">我的群组</div>
              <div class="flex space-x-2">
                <button
                  @click="showJoinGroupModal = true"
                  class="text-xs bg-green-600 text-white py-1 px-3 rounded-md hover:bg-green-700"
                >
                  加入群组
                </button>
                <button
                  @click="showCreateGroupModal = true"
                  class="text-xs bg-primary text-white py-1 px-3 rounded-md hover:bg-blue-600"
                >
                  创建群组
                </button>
              </div>
            </div>

            <!-- 群组列表 -->
            <div
              v-for="groupDef in userGroups"
              :key="groupDef.id"
              @click="openGroupChat(groupDef.id)"
              class="p-4 hover:bg-gray-50 cursor-pointer"
              :class="{ 'bg-gray-50': chatStore.currentChat === `group_${groupDef.id}` }"
            >
              <div class="flex">
                <div class="h-10 w-10 rounded-full flex items-center justify-center bg-indigo-100 text-2xl">
                  {{ processGroupAvatar(groupDef.group_avatar) }}
                </div>
                <div class="ml-3 flex-1">
                  <div class="flex items-center justify-between">
                    <div class="font-medium">{{ groupDef.name }}</div>
                    <div v-if="getChatDataForGroup(groupDef.id)?.lastMessage?.createdAt" class="text-xs text-gray-500">
                      {{ formatTime(getChatDataForGroup(groupDef.id)!.lastMessage.createdAt) }}
                    </div>
                  </div>
                  <div class="text-sm text-gray-500 truncate">
                    <span v-if="getChatDataForGroup(groupDef.id)?.lastMessage?.content">
                      {{ getChatDataForGroup(groupDef.id)!.lastMessage.content }}
                    </span>
                    <span v-else class="italic">暂无消息</span>
                  </div>
                </div>
                <div v-if="(getChatDataForGroup(groupDef.id)?.unreadCount || 0) > 0" class="ml-2 h-5 w-5 bg-red-500 rounded-full flex items-center justify-center text-white text-xs">
                  {{ getChatDataForGroup(groupDef.id)!.unreadCount }}
                </div>
              </div>
            </div>

            <!-- 我的好友标题 -->
            <div class="p-3 bg-gray-50 flex justify-between items-center">
              <div class="font-medium text-sm">我的好友</div>
            </div>

            <!-- 好友列表 -->
            <div
              v-for="friend in chatStore.friends"
              :key="friend._id"
              @click="openChatWithFriend(friend._id)"
              class="p-4 hover:bg-gray-50 cursor-pointer"
            >
              <div class="flex items-center">
                <UserAvatar
                  :username="friend.username"
                  :avatar="friend.avatar"
                  :userId="friend._id"
                  size="md"
                  :clickable="true"
                />
                <div class="ml-3">
                  <div class="font-medium">{{ friend.username }}</div>
                  <div class="text-xs text-gray-500 flex items-center">
                    <span
                      class="inline-block h-2 w-2 rounded-full mr-1"
                      :class="friend.status === 'online' ? 'bg-green-500' : 'bg-gray-400'"
                    ></span>
                    <span>{{ friend.status === 'online' ? '在线' : '离线' }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 没有联系人提示 -->
            <div v-if="chatStore.friends.length === 0 && userGroups.length === 0" class="p-4 text-center text-gray-500">
              暂无联系人，点击右上角添加好友或创建群组
            </div>
          </div>
        </div>
      </aside>

      <!-- 中间聊天区域 -->
      <section class="flex-1 flex flex-col bg-gray-50">
        <div v-if="!chatStore.currentChat" class="flex-1 flex flex-col items-center justify-center text-gray-400">
          <div class="text-xl mb-2">轻语</div>
          <div>选择一个联系人开始聊天</div>
        </div>

        <template v-else>
          <!-- 聊天头部 -->
          <div class="py-2 px-4 bg-white border-b border-gray-200">
            <div class="flex items-center">
              <!-- 私聊用户头像和信息 -->
              <template v-if="!chatStore.currentChat.startsWith('group_')">
                <UserAvatar
                  :username="chatStore.currentChatUser?.username"
                  :avatar="chatStore.currentChatUser?.avatar"
                  :userId="chatStore.currentChatUser?._id"
                  size="sm"
                  :clickable="true"
                  class="mr-2"
                />
                <div>
                  <div class="font-medium">{{ chatStore.currentChatUser?.username }}</div>
                  <div class="text-xs text-gray-500 flex items-center">
                    <span
                      class="inline-block h-2 w-2 rounded-full mr-1"
                      :class="chatStore.currentChatUser?.status === 'online' ? 'bg-green-500' : 'bg-gray-400'"
                    ></span>
                    <span>{{ chatStore.currentChatUser?.status === 'online' ? '在线' : '离线' }}</span>
                  </div>
                </div>
              </template>

              <!-- 群聊信息 -->
              <template v-else>
                <div class="h-8 w-8 rounded-full bg-indigo-100 text-xl flex items-center justify-center mr-2">
                  {{ processGroupAvatar(currentGroupInfo?.group_avatar) }}
                </div>
                <div>
                  <div class="font-medium">
                    {{ currentGroupInfo?.name || '群聊' }}
                    <span v-if="isCurrentUserLeftGroup" class="text-xs text-gray-500 ml-1">(已退出)</span>
                  </div>
                  <div class="text-xs text-gray-500">
                    <span v-if="!isCurrentUserLeftGroup">{{ currentGroupInfo?.members?.length || 0 }}人</span>
                    <span v-else>历史群聊</span>
                  </div>
                </div>
              </template>

              <div class="ml-auto flex items-center space-x-3">
                <div v-if="chatStore.isTyping" class="text-xs text-gray-500 italic">
                  正在输入...
                </div>
                <div class="relative">
                  <button
                    @click="showChatMenu = !showChatMenu"
                    class="text-gray-500 hover:text-gray-700 p-1 rounded-full hover:bg-gray-100"
                    title="更多选项"
                  >
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                      <path d="M10 6a2 2 0 110-4 2 2 0 010 4zM10 12a2 2 0 110-4 2 2 0 010 4zM10 18a2 2 0 110-4 2 2 0 010 4z" />
                    </svg>
                  </button>
                  <!-- 聊天选项菜单 -->
                  <div v-if="showChatMenu" class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg z-20">
                    <div class="py-1">
                      <a
                        @click="openSearchMessages"
                        class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer"
                      >
                        搜索聊天记录
                      </a>
                      <!-- 创建群组选项 -->
                      <a
                        @click="showCreateGroupModal = true; showChatMenu = false"
                        class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer"
                      >
                        创建群组
                      </a>
                      <!-- 群聊才显示群组管理选项 -->
                      <template v-if="chatStore.currentChat && chatStore.currentChat.startsWith('group_')">
                        <!-- 仅当前群成员可见的选项 -->
                        <template v-if="!isCurrentUserLeftGroup">
                          <a
                            @click="showInviteToGroupModal = true; showChatMenu = false"
                            class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer"
                          >
                            邀请好友加入
                          </a>
                          <a
                            class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer"
                            @click="showGroupInfo = true; showChatMenu = false"
                          >
                            查看群组信息
                          </a>
                        </template>
                        <!-- 已退出群组的提示 -->
                        <template v-else>
                          <div class="px-4 py-2 text-sm text-gray-500 italic">
                            您已退出该群组
                          </div>
                        </template>
                      </template>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 消息显示区域 -->
          <div class="flex-1 p-4 overflow-y-auto" ref="messageContainer">
            <!-- 私聊消息 -->
            <div v-if="!chatStore.currentChat?.startsWith('group_')">
              <div v-if="chatStore.messages.length === 0" class="h-full flex items-center justify-center text-gray-400">
                暂无消息
              </div>
              <template v-else>
                <div
                  v-for="(message, index) in chatStore.messages"
                  :key="message._id"
                  class="mb-4 last:mb-0"
                >
                  <!-- 日期分隔线 -->
                  <div
                    v-if="index === 0 || !isSameDay(message.createdAt, chatStore.messages[index - 1].createdAt)"
                    class="text-center text-xs text-gray-500 mb-4"
                  >
                    {{ formatDate(message.createdAt) }}
                  </div>

                  <!-- 消息气泡 -->
                  <div
                    class="flex"
                    :id="`message-${message._id}`"
                    :class="{ 'flex-row-reverse': message.sender._id === authStore.user?._id }"
                  >
                    <UserAvatar
                      :username="message.sender.username"
                      :avatar="message.sender.avatar"
                      :userId="message.sender._id"
                      size="sm"
                      :clickable="true"
                    />
                    <div
                      class="mx-2 px-3 py-2 rounded-lg"
                      :class="message.sender._id === authStore.user?._id ? 'message-sent' : 'message-received'"
                    >
                      {{ message.content }}
                    </div>
                    <div class="text-xs text-gray-500 self-end mb-1">
                      {{ formatMessageTime(message.createdAt) }}
                    </div>
                  </div>
                </div>
              </template>
            </div>

            <!-- 群聊消息 -->
            <div v-else>
              <!-- 群组已解散提示 -->
              <div v-if="isCurrentGroupDisbanded" class="bg-yellow-50 border border-yellow-200 rounded-lg p-3 mb-4 text-center">
                <div class="text-yellow-800 text-sm font-medium">
                  🚨 该群组已于 {{ formatDate(currentGroupInfo?.disbanded_at || '') }} 解散
                </div>
                <div class="text-yellow-600 text-xs mt-1">
                  您仍可以查看以往的聊天记录，但无法发送新消息
                </div>
              </div>
              
              <!-- 已退出群组提示 -->
              <div v-if="isCurrentUserLeftGroup" class="bg-blue-50 border border-blue-200 rounded-lg p-3 mb-4 text-center">
                <div class="text-blue-800 text-sm font-medium">
                  ℹ️ 您已退出该群组
                </div>
                <div class="text-blue-600 text-xs mt-1">
                  您可以查看退出前的聊天记录，但无法发送新消息或查看群组详情
                </div>
              </div>
              
              <!-- 待处理加入请求提示 (仅群管理员可见) -->
              <div v-if="canManageCurrentGroup && pendingJoinRequestsCount > 0" class="bg-green-50 border border-green-200 rounded-lg p-3 mb-4">
                <div class="flex items-center justify-between">
                  <div class="flex items-center">
                    <div class="text-green-600 mr-2">🔔</div>
                    <div>
                      <div class="text-green-800 text-sm font-medium">
                        有 {{ pendingJoinRequestsCount }} 个待处理的加入申请
                      </div>
                      <div class="text-green-600 text-xs">
                        点击右上角菜单 → 查看群组信息 → 管理加入申请
                      </div>
                    </div>
                  </div>
                  <button 
                    @click="openGroupJoinRequests"
                    class="px-3 py-1 text-xs bg-green-600 text-white rounded-md hover:bg-green-700"
                  >
                    处理申请
                  </button>
                </div>
              </div>

              <div v-if="chatStore.groupMessages.length === 0" class="h-full flex items-center justify-center text-gray-400">
                暂无群组消息
              </div>
              <template v-else>
                <div
                  v-for="(message, index) in chatStore.groupMessages"
                  :key="message.id"
                  class="mb-4 last:mb-0"
                >
                  <!-- 日期分隔线 -->
                  <div
                    v-if="index === 0 || !isSameDay(message.created_at, chatStore.groupMessages[index - 1].created_at)"
                    class="text-center text-xs text-gray-500 mb-4"
                  >
                    {{ formatDate(message.created_at) }}
                  </div>

                  <!-- 群组消息气泡 -->
                  <div
                    class="flex"
                    :id="`group-message-${message.id}`"
                    :class="{ 'flex-row-reverse': message.sender.id === authStore.user?._id }"
                  >
                    <UserAvatar
                      :username="message.sender.username"
                      :avatar="message.sender.avatar"
                      :userId="message.sender.id"
                      size="sm"
                      :clickable="true"
                    />
                    <div
                      class="mx-2 px-3 py-2 rounded-lg"
                      :class="message.sender.id === authStore.user?._id ? 'message-sent' : 'message-received'"
                    >
                      {{ message.content }}
                    </div>
                    <div class="text-xs text-gray-500 self-end mb-1">
                      {{ formatMessageTime(message.created_at) }}
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>

          <!-- 消息输入区域 -->
          <div class="bg-white border-t border-gray-200 p-4">
            <!-- 群组已解散时的禁用提示 -->
            <div v-if="chatStore.currentChat?.startsWith('group_') && isCurrentGroupDisbanded" class="text-center py-3">
              <div class="text-gray-500 text-sm">
                🚫 群组已解散，无法发送消息
              </div>
            </div>
            <!-- 已退出群组时的禁用提示 -->
            <div v-else-if="chatStore.currentChat?.startsWith('group_') && isCurrentUserLeftGroup" class="text-center py-3">
              <div class="text-gray-500 text-sm">
                🚫 您已退出该群组，无法发送消息
              </div>
            </div>
            <!-- 正常消息输入 -->
            <div v-else class="flex space-x-2">
              <div class="flex-1 relative">
                <textarea
                  v-model="messageInput"
                  @input="handleMessageInput"
                  @keydown.enter.prevent="sendMessage"
                  placeholder="输入消息..."
                  class="w-full form-input resize-none py-2 h-12 pr-10"
                  ref="messageTextarea"
                ></textarea>
                <div class="absolute right-2 bottom-2 flex items-center">
                  <EmojiPicker @select="addEmoji" />
                </div>
              </div>
              <button
                @click="sendMessage"
                class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-400 transition-colors"
                :disabled="!messageInput.trim() || sendingMessage"
              >
                {{ sendingMessage ? '发送中...' : '发送' }}
              </button>
            </div>
          </div>
        </template>
      </section>
    </main>

    <!-- 添加好友模态框 -->
    <div v-if="showAddFriendModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-10">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-medium">添加好友</h3>
          <button @click="showAddFriendModal = false" class="text-gray-400 hover:text-gray-500">
            &times;
          </button>
        </div>
        <div class="mb-4">
          <input
            v-model="searchKeyword"
            @input="handleSearch"
            type="text"
            placeholder="输入用户名或邮箱"
            class="form-input w-full"
          />
        </div>
        <div v-if="searchLoading" class="text-center py-4">
          正在搜索...
        </div>
        <div v-else-if="searchError" class="text-center py-4 text-red-500">
          {{ searchError }}
        </div>
        <div v-else-if="searchResults.length === 0 && searchKeyword" class="text-center py-4 text-gray-500">
          未找到相关用户
        </div>
        <div v-else class="max-h-60 overflow-y-auto">
          <div
            v-for="user in searchResults"
            :key="user._id"
            class="p-2 border-b border-gray-200 last:border-0 flex items-center"
          >
            <div class="h-8 w-8 rounded-full bg-gray-300 flex items-center justify-center text-gray-700 font-semibold cursor-pointer" @click="viewUserProfile(user._id)">
              <div v-if="user.avatar" class="h-full w-full rounded-full bg-cover bg-center" :style="`background-image: url('${user.avatar}')`"></div>
              <template v-else>{{ user.username[0].toUpperCase() }}</template>
            </div>
            <div class="ml-2 flex-1">
              <div class="font-medium">{{ user.username }}</div>
              <div class="text-xs text-gray-500">{{ user.email }}</div>
            </div>
            <button
              @click="sendFriendRequest(user._id)"
              class="px-2 py-1 text-xs bg-primary text-white rounded"
              :disabled="sendingRequest === user._id"
            >
              {{ sendingRequest === user._id ? '请求中...' : '添加' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索消息模态框 -->
    <SearchMessagesModal
      v-if="showSearchModal && chatStore.currentChat"
      :userId="chatStore.currentChat"
      @close="showSearchModal = false"
      @select-message="scrollToMessage"
    />

    <!-- 创建群组模态框 -->
    <CreateGroupModal
      :isOpen="showCreateGroupModal"
      @close="showCreateGroupModal = false"
      @created="handleGroupCreated"
    />

    <!-- 加入群组模态框 -->
    <JoinGroupModal
      :isOpen="showJoinGroupModal"
      @close="showJoinGroupModal = false"
      @joined="handleGroupJoined"
    />

    <!-- 邀请到群组模态框 -->
    <InviteToGroupModal
      v-if="showInviteToGroupModal"
      :isOpen="showInviteToGroupModal"
      :groupId="currentGroupId"
      :groupName="currentGroupInfo?.name || ''"
      @close="showInviteToGroupModal = false"
    />

    <!-- 群组信息模态框 -->
    <GroupInfoModal
      v-if="showGroupInfo"
      :isOpen="showGroupInfo"
      :groupId="currentGroupId"
      @close="showGroupInfo = false"
      @invite="showInviteToGroupModal = true; showGroupInfo = false"
      @manage-requests="openGroupJoinRequests(); showGroupInfo = false"
      @left="handleLeftGroup"
    />

    <!-- 群组加入申请管理模态框 -->
    <GroupJoinRequests
      v-if="showGroupJoinRequests"
      :isOpen="showGroupJoinRequests"
      :groupId="currentGroupId"
      @close="showGroupJoinRequests = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useChatStore } from '@/stores/chat'
import { useRouter } from 'vue-router'
import EmojiPicker from '@/components/EmojiPicker.vue'
import UserAvatar from '@/components/UserAvatar.vue'
import SearchMessagesModal from '@/components/SearchMessagesModal.vue'
import CreateGroupModal from '@/components/CreateGroupModal.vue'
import JoinGroupModal from '@/components/JoinGroupModal.vue'
import InviteToGroupModal from '@/components/InviteToGroupModal.vue'
import GroupInfoModal from '@/components/GroupInfoModal.vue'
import GroupInvitations from '@/components/GroupInvitations.vue'
import GroupJoinRequests from '@/components/GroupJoinRequests.vue'
import axios from 'axios'

// 获取store
const authStore = useAuthStore()
const chatStore = useChatStore()
const router = useRouter()

// 消息相关
const messageInput = ref('')
const messageContainer = ref<HTMLElement | null>(null)
const messageTextarea = ref<HTMLTextAreaElement | null>(null)
const sendingMessage = ref(false)

// 搜索好友
const showAddFriendModal = ref(false)
const searchKeyword = ref('')
const searchResults = ref<any[]>([])
const searchLoading = ref(false)
const searchError = ref('')
const sendingRequest = ref('')

// 菜单相关
const showChatMenu = ref(false)

// 搜索消息模态框
const showSearchModal = ref(false)

// 群组相关
const showCreateGroupModal = ref(false)
const showJoinGroupModal = ref(false)
const showInviteToGroupModal = ref(false)
const showGroupInfo = ref(false)
const showGroupJoinRequests = ref(false)
const userGroups = ref<any[]>([])
const loadingGroups = ref(false)
const groupInvitations = ref<any[]>([])
const loadingInvitations = ref(false)
const currentGroupId = ref('')
const currentGroupInfo = ref<any>(null)
const pendingJoinRequestsCount = ref(0)

// 计算好友请求数量
const friendRequestsCount = computed(() => chatStore.friendRequests.length)

// 计算群组邀请数量
const groupInvitationsCount = computed(() => groupInvitations.value.length)

// 计算群组未读消息总数
const unreadGroupMessagesCount = computed(() => {
  return chatStore.chats
    .filter(chat => chat.isGroup)
    .reduce((sum, groupChat) => sum + (groupChat.unreadCount || 0), 0);
})

// 计算当前群组是否已解散
const isCurrentGroupDisbanded = computed(() => {
  return currentGroupInfo.value?.status === 'disbanded'
})

// 计算当前用户是否已退出群组
const isCurrentUserLeftGroup = computed(() => {
  return currentGroupInfo.value?.status === 'left' || currentGroupInfo.value?.isCurrentMember === false
})

// 计算当前用户是否可以管理当前群组
const canManageCurrentGroup = computed(() => {
  if (!currentGroupInfo.value || !authStore.user) return false
  
  // 检查是否是群主
  if (currentGroupInfo.value.creator_id === authStore.user._id) return true
  
  // 检查是否是管理员
  const currentUserMember = currentGroupInfo.value.members?.find((m: any) => m.user_id === authStore.user._id)
  return currentUserMember?.role === 'admin'
})

// 全局搜索相关
const globalSearchKeyword = ref('')
const showGlobalSearchResults = ref(false)
const globalSearchLoading = ref(false)
const filteredContacts = ref<any[]>([])
const filteredChats = ref<any[]>([])
const globalSearchTimeout = ref<number | null>(null)

// 监听全局搜索关键词变化
watch(globalSearchKeyword, (newValue) => {
  // 清除之前的定时器
  if (globalSearchTimeout.value) {
    clearTimeout(globalSearchTimeout.value)
    globalSearchTimeout.value = null
  }
  
  if (!newValue.trim()) {
    filteredContacts.value = []
    filteredChats.value = []
    showGlobalSearchResults.value = false
    return
  }
  
  if (newValue.trim().length < 2) {
    filteredContacts.value = []
    filteredChats.value = []
    return
  }
  
  // 300ms 防抖
  globalSearchTimeout.value = setTimeout(() => {
    performGlobalSearch()
  }, 300) as unknown as number
})

// 执行全局搜索
function performGlobalSearch() {
  if (!globalSearchKeyword.value.trim()) {
    filteredContacts.value = []
    filteredChats.value = []
    return
  }

  globalSearchLoading.value = true

  try {
    const keyword = globalSearchKeyword.value.toLowerCase()
    
    // 从好友和群组中搜索联系人
    const allContacts = [
      ...chatStore.friends.map(friend => ({
        ...friend,
        isGroup: false
      })),
      ...userGroups.value.map(group => ({
        _id: `group_${group.id}`,
        username: group.name,
        avatar: group.group_avatar || '👥',
        isGroup: true,
        memberCount: group.member_count || 0
      }))
    ]
    
    filteredContacts.value = allContacts.filter(contact => 
      contact.username.toLowerCase().includes(keyword)
    )

    // 从聊天记录中搜索
    filteredChats.value = chatStore.chats.filter(chat => 
      chat.username.toLowerCase().includes(keyword) ||
      chat.lastMessage.content.toLowerCase().includes(keyword)
    )
  } catch (error) {
    console.error('全局搜索失败:', error)
  } finally {
    globalSearchLoading.value = false
  }
}

// 全局搜索处理（兼容原有调用）
async function handleGlobalSearch() {
  // 这个方法现在主要用于 @input 事件，实际搜索由 watch 处理
  showGlobalSearchResults.value = true
}

// 初始化数据
onMounted(async () => {
  await chatStore.initData()
  // 滚动到底部
  scrollToBottom()
  // 监听全局点击事件，用于关闭菜单
  document.addEventListener('click', handleClickOutside)
  // 加载群组数据
  loadGroupData()
})

// 清理资源
onUnmounted(() => {
  chatStore.cleanup()
  document.removeEventListener('click', handleClickOutside)
})

// 监听消息变化，自动滚动到底部
watch(() => chatStore.messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 监听activeTab变化，加载对应数据
watch(() => chatStore.activeTab, (newTab) => {
  if (newTab === 'contacts') {
    loadGroupData()
  }
})

// 加载群组相关数据
async function loadGroupData() {
  if (chatStore.activeTab !== 'contacts') return

  loadingGroups.value = true
  loadingInvitations.value = true

  try {
    // 加载用户的群组
    const groupsResponse = await axios.get('/api/groups')
    userGroups.value = groupsResponse.data

    // 加载群组邀请
    const invitationsResponse = await axios.get('/api/groups/invitations')
    groupInvitations.value = invitationsResponse.data
  } catch (error) {
    console.error('加载群组数据失败:', error)
  } finally {
    loadingGroups.value = false
    loadingInvitations.value = false
  }
}

// 处理群组邀请响应
function handleGroupInvitationResponse({ invitationId, action }: { invitationId: string, action: string }) {
  // 从列表中移除已处理的邀请
  groupInvitations.value = groupInvitations.value.filter(inv => inv.id !== invitationId)

  // 如果接受了邀请，重新加载群组列表
  if (action === 'accepted') {
    loadGroupData()
  }
}

// 处理退出或解散群组
function handleLeftGroup() {
  // 关闭当前聊天
  chatStore.setCurrentChat(null)
  // 重新加载群组列表
  loadGroupData()
}

// 打开群聊
async function openGroupChat(groupId: string) {
  // 如果已经在当前群聊，则不做任何操作
  if (chatStore.currentChat === `group_${groupId}`) {
    return
  }

  try {
    console.log('打开群聊:', groupId)

    // 设置当前群组ID
    currentGroupId.value = groupId

    // 立即更新聊天列表中的未读计数，使红点立即消失
    const chatIndex = chatStore.chats.findIndex(chat => chat._id === `group_${groupId}`);
    if (chatIndex !== -1 && chatStore.chats[chatIndex].unreadCount > 0) {
      chatStore.chats[chatIndex].unreadCount = 0;
    }

    // 获取群组详情
    const response = await axios.get(`/api/groups/${groupId}`)
    currentGroupInfo.value = response.data

    // 等待下一个tick，确保计算属性更新后再检查权限
    await nextTick()
    
    // 如果当前用户是管理员，加载待处理请求数量
    if (canManageCurrentGroup.value) {
      loadPendingJoinRequestsCount(groupId)
    }

    // 加载群组消息
    await chatStore.fetchGroupMessages(groupId)

    // 设置当前聊天标识为群组ID（添加前缀以区分）
    chatStore.setCurrentChat(`group_${groupId}`)

    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  } catch (error) {
    console.error('打开群聊失败:', error)
    alert('打开群聊失败，请重试')
  }
}

// 创建群组
function handleGroupCreated(newGroup: any) {
  userGroups.value.unshift(newGroup)
  openGroupChat(newGroup.id)
}

// 加入群组
function handleGroupJoined(group: any) {
  // 重新加载群组列表
  loadGroupData()
}

// 打开邀请好友到群组模态框
function openInviteToGroupModal() {
  if (!currentGroupId.value) {
    console.error('没有选择群组')
    return
  }
  showInviteToGroupModal.value = true
}

// 打开群组加入申请管理模态框
function openGroupJoinRequests() {
  if (!currentGroupId.value) {
    console.error('没有选择群组')
    return
  }
  showGroupJoinRequests.value = true
}

// 加载待处理加入请求数量
async function loadPendingJoinRequestsCount(groupId: string) {
  try {
    const response = await axios.get(`/api/groups/${groupId}/join-requests`)
    pendingJoinRequestsCount.value = response.data.length
    console.log(`群组 ${groupId} 有 ${response.data.length} 个待处理请求`)
  } catch (err: any) {
    // 如果没有权限访问，忽略错误
    if (err.response?.status !== 403) {
      console.error('加载待处理请求数量失败:', err)
    }
    pendingJoinRequestsCount.value = 0
  }
}

// 滚动到底部
function scrollToBottom() {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

// 处理消息输入
function handleMessageInput() {
  if (chatStore.currentChat) {
    chatStore.sendTypingStatus(chatStore.currentChat, true)
  }
}

// 发送消息
async function sendMessage() {
  if (!messageInput.value.trim() || !chatStore.currentChat || sendingMessage.value) return

  sendingMessage.value = true

  try {
    // 检查是否是群组消息
    if (chatStore.currentChat.startsWith('group_')) {
      const groupId = chatStore.currentChat.replace('group_', '')
      console.log(`准备发送群组消息到群组ID: ${groupId}, 内容: ${messageInput.value}`)

      const result = await chatStore.sendGroupMessage(groupId, messageInput.value)
      console.log('群组消息发送结果:', result)

      if (result.success) {
        messageInput.value = ''
        scrollToBottom()
      } else {
        console.error('群组消息发送失败:', result.message)
        alert(`发送失败: ${result.message}`)
      }
    } else {
      // 私聊消息
      console.log(`准备发送私聊消息到用户ID: ${chatStore.currentChat}, 内容: ${messageInput.value}`)

      const result = await chatStore.sendMessage(chatStore.currentChat, messageInput.value)
      console.log('私聊消息发送结果:', result)

      if (result.success) {
        messageInput.value = ''
        scrollToBottom()
      } else {
        console.error('消息发送失败:', result.message)
        alert(`发送失败: ${result.message}`)
      }
    }
  } catch (error) {
    console.error('发送消息时出错:', error)
    alert('发送消息失败，请重试')
  } finally {
    sendingMessage.value = false

    if (chatStore.currentChat && !chatStore.currentChat.startsWith('group_')) {
      chatStore.sendTypingStatus(chatStore.currentChat, false)
    }
  }
}

// 处理好友请求
async function handleFriendRequest(requestId: string, action: 'accepted' | 'rejected') {
  await chatStore.respondToFriendRequest(requestId, action)
}

// 搜索用户
async function handleSearch() {
  if (!searchKeyword.value.trim()) {
    searchResults.value = []
    return
  }

  searchLoading.value = true
  searchError.value = ''

  try {
    const result = await chatStore.searchUsers(searchKeyword.value)
    if (result.success) {
      searchResults.value = result.users
    } else {
      searchError.value = '搜索失败，请重试'
    }
  } catch (error) {
    searchError.value = '搜索失败，请重试'
  } finally {
    searchLoading.value = false
  }
}

// 发送好友请求
async function sendFriendRequest(userId: string) {
  sendingRequest.value = userId

  try {
    const result = await chatStore.sendFriendRequest(userId)
    if (result.success) {
      // 移除搜索结果中的该用户
      searchResults.value = searchResults.value.filter(user => user._id !== userId)

      if (searchResults.value.length === 0) {
        showAddFriendModal.value = false
      }
    } else {
      searchError.value = result.message
    }
  } catch (error) {
    searchError.value = '发送请求失败，请重试'
  } finally {
    sendingRequest.value = ''
  }
}

// 格式化时间
function formatTime(timestamp: string): string {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  // 不到一分钟显示"刚刚"
  if (diff < 60 * 1000) {
    return '刚刚'
  }

  // 不到一小时显示分钟
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  }

  // 不到24小时显示小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  }

  // 不到7天显示天数
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  }

  // 同一年显示月日
  if (date.getFullYear() === now.getFullYear()) {
    return `${date.getMonth() + 1}月${date.getDate()}日`
  }

  // 不同年显示年月日
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

// 格式化消息时间（只显示时分）
function formatMessageTime(timestamp: string): string {
  const date = new Date(timestamp)
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 格式化日期
function formatDate(timestamp: string): string {
  const date = new Date(timestamp)
  const now = new Date()
  const isToday = date.getDate() === now.getDate() &&
                  date.getMonth() === now.getMonth() &&
                  date.getFullYear() === now.getFullYear()

  const isYesterday = date.getDate() === now.getDate() - 1 &&
                      date.getMonth() === now.getMonth() &&
                      date.getFullYear() === now.getFullYear()

  if (isToday) {
    return '今天'
  }

  if (isYesterday) {
    return '昨天'
  }

  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
}

// 判断两个时间戳是否是同一天
function isSameDay(timestamp1: string, timestamp2: string): boolean {
  const date1 = new Date(timestamp1)
  const date2 = new Date(timestamp2)

  return date1.getDate() === date2.getDate() &&
         date1.getMonth() === date2.getMonth() &&
         date1.getFullYear() === date2.getFullYear()
}

// 查看用户资料
function viewUserProfile(userId: string) {
  // 如果是自己的ID，跳转到个人资料页面
  if (userId === authStore.user?._id) {
    router.push('/profile/me');
  } else {
    router.push(`/profile/${userId}`);
  }
}

// 添加表情
function addEmoji(emoji: string) {
  console.log('选择了表情:', emoji);
  if (messageTextarea.value) {
    const textarea = messageTextarea.value;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;

    // 更新 messageInput 的值
    messageInput.value =
      messageInput.value.substring(0, start) +
      emoji +
      messageInput.value.substring(end);

    // 更新光标位置到插入的表情之后
    nextTick(() => {
      textarea.selectionStart = textarea.selectionEnd = start + emoji.length;
      textarea.focus(); // 重新聚焦，确保光标可见
    });
  } else {
    // 如果textarea的引用不存在，则回退到追加模式
    messageInput.value += emoji;
  }
}

// 滚动到特定消息
function scrollToMessage(message: any) {
  // 先确保消息列表已经加载
  if (message.sender._id !== chatStore.currentChat && message.receiver._id !== chatStore.currentChat) {
    return;
  }

  // 查找消息所在位置
  const messageElement = document.getElementById(`message-${message._id}`);
  if (messageElement) {
    messageElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
    // 添加短暂的高亮效果
    messageElement.classList.add('bg-yellow-100');
    setTimeout(() => {
      messageElement.classList.remove('bg-yellow-100');
    }, 2000);
  }
}

// 打开搜索消息模态框
function openSearchMessages() {
  showSearchModal.value = true
  showChatMenu.value = false
}

// 点击页面其他区域关闭菜单
function handleClickOutside(event: MouseEvent) {
  const target = event.target as Element
  if (!target.closest('.relative')) {
    showChatMenu.value = false
  }
}

// 打开聊天窗口
function openChatWithFriend(userId: string) {
  // 如果已经在当前聊天，则不做任何操作
  if (chatStore.currentChat === userId) {
    console.log('已经在当前聊天窗口，无需重复加载');
    return;
  }

  // 重置群组相关状态
  currentGroupId.value = ''
  currentGroupInfo.value = null

  // 立即更新聊天列表中的未读计数，使红点立即消失
  const chatIndex = chatStore.chats.findIndex(chat => chat._id === userId);
  if (chatIndex !== -1 && chatStore.chats[chatIndex].unreadCount > 0) {
    chatStore.chats[chatIndex].unreadCount = 0;
  }

  // 加载聊天记录
  chatStore.fetchMessages(userId);
}

// 获取群组在chatStore中的动态数据
function getChatDataForGroup(groupId: string) {
  return chatStore.chats.find(chat => chat.isGroup && chat._id === `group_${groupId}`);
}

// 清空全局搜索
function clearGlobalSearch() {
  globalSearchKeyword.value = ''
  filteredContacts.value = []
  filteredChats.value = []
  showGlobalSearchResults.value = false
}

// 处理全局搜索结果
function handleSearchBlur() {
  showGlobalSearchResults.value = false
}

// 高亮搜索关键词
function highlightSearchKeyword(text: string): string {
  if (!globalSearchKeyword.value.trim()) return text
  const regex = new RegExp(`(${globalSearchKeyword.value})`, 'gi')
  return text.replace(regex, '<span class="bg-yellow-100">$1</span>')
}

// 打开联系人聊天
function openContactChat(contact: any) {
  clearGlobalSearch()
  
  if (contact.isGroup) {
    // 群组聊天
    const groupId = contact._id.replace('group_', '')
    openGroupChat(groupId)
  } else {
    // 私聊
    openChatWithFriend(contact._id)
  }
}

// 处理群组头像
function processGroupAvatar(avatar: string | null): string {
  if (!avatar) return '👥'
  
  // 如果包含emoji前缀，去除前缀
  if (avatar.startsWith('emoji:')) {
    return avatar.replace('emoji:', '')
  }
  
  // 如果是图片URL，返回默认emoji（因为这里是纯文本显示）
  if (avatar.startsWith('data:image/') || avatar.startsWith('http')) {
    return '👥'
  }
  
  // 直接返回emoji
  return avatar || '👥'
}
</script>

<style scoped>
.message-received {
  background-color: #f0f0f0;
  border-top-left-radius: 0;
  align-self: flex-start;
}

/* 搜索结果高亮效果 */
.bg-yellow-100 {
  background-color: rgba(254, 249, 195, 0.4) !important;
  transition: background-color 0.5s ease;
}

/* 表单输入样式 */
.form-input {
  @apply block rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-50;
}
</style>